package com.example.myapplication.activity;


import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.myapplication.R;
import com.example.myapplication.utils.WifiUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

public class PositionActivity extends AppCompatActivity implements SensorEventListener {

    private SensorManager sensorManager;
    public static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;
    private Sensor sensor;

    private Button tv_back;
    private TextView mMagneticField;
    private Sensor accelerometer;
    private WifiUtils wifi;
    private float[] magneticValues;
    private float[] accelerometerValues;
    private float[] rotationMatrix = new float[9];
    private float[] worldCoordinates = new float[3];
    private float[] angle = new float[3];
    //载体的坐标
    private float[] load = new float[3];
    private String globle_x;
    private String globle_y;
    private String globle_z;
    private String load_x;
    private String load_y;
    private String load_z;
    private Button collect;
    private Button flush;

    private String wifi_strength;
    private String position;
    private EditText et_ps;
    private EditText et_ser;
    private String serial;

    private Button gps;
    private TextView tv_show;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_position);

        //去除默认标题栏
        ActionBar actionBar=getSupportActionBar();
        if(actionBar!=null){
            actionBar.hide();
        }


        flush = findViewById(R.id.flush);
        mMagneticField=findViewById(R.id.tv_magnetic_field);
        sensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensor=sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        et_ps = (EditText) findViewById(R.id.position);
        et_ser = (EditText) findViewById(R.id.serial);
        collect = (Button)findViewById(R.id.colletion);
        gps = (Button)findViewById(R.id.gps);
        tv_show = (TextView)findViewById(R.id.show);
        wifi = new WifiUtils(this,this);
        wifi_strength = wifi.getWifi().toString();

        flush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wifi_strength = wifi.getWifi().toString();
                updateUI();
            }
        });

        tv_back = (Button)findViewById(R.id.tv_back);
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PositionActivity.this.finish();
            }
        });

//        CountDownTimer timer = new CountDownTimer(1000000000,1000) {
//            @Override
//            public void onTick(long l) {
//                wifi_strength = wifi.getWifi().toString();
//            }
//
//            @Override
//            public void onFinish() {
//            }
//        };
//        wifi_strength = wifi.getWifi().toString();
        collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wifi_strength = wifi.getWifi().toString();
                position = et_ps.getText().toString().trim();
                serial = et_ser.getText().toString().trim();
                String p1 = globle_x+":"+globle_y+":"+globle_z;
                String p2 = load_x+":"+load_y+":"+load_z;
                OkHttpUtils
                        .post()
                        .url("http://121.36.92.128:8086/load")
                        .addParams("serial",serial)
                        .addParams("position",position)
                        .addParams("wifi",wifi_strength)
                        .addParams("global", p1)
                        .addParams("load",p2)
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(okhttp3.Call call, Exception e, int id) {
                                System.out.println(e.toString());
                            }

                            @Override
                            public void onResponse(String response, int i) {
                                if(response.equals("true")){
                                    Toast.makeText(PositionActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                                }else{
                                    Toast.makeText(PositionActivity.this, "保存失败", Toast.LENGTH_LONG).show();
                                }
                            }
                        });
            }
        });


        gps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wifi_strength = wifi.getWifi().toString();
                if(!wifi_strength.isEmpty() && !load_x.isEmpty() && !load_y.isEmpty() && !load_z.isEmpty())
                {
                    OkHttpUtils
                            .get()
                            .url("http://121.36.92.128:8086/position")
                            .addParams("wifi",wifi_strength)
                            .addParams("load",globle_x+":"+globle_y+":"+globle_z)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    System.out.println(e.toString());
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    if(!response.isEmpty()){
                                        tv_show.setText(response);
                                    }
                                }
                            });
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sensorManager != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
            sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this,sensor);
        sensorManager.unregisterListener(this,accelerometer);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
//        wifi_strength = wifi.getWifi().toString();
        switch (event.sensor.getType()) {
            case Sensor.TYPE_MAGNETIC_FIELD:
                magneticValues = event.values.clone();
                break;
            case Sensor.TYPE_ACCELEROMETER:
                accelerometerValues = event.values.clone();
                break;
        }
        if(magneticValues != null && accelerometerValues != null)
        {
            convertToWorldCoordinates();
            if (accelerometerValues != null && magneticValues != null) {
                updateUI();
            }
        }
    }




    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    private void convertToWorldCoordinates() {
        SensorManager.getRotationMatrix(rotationMatrix, null, accelerometerValues, magneticValues);
        SensorManager.getOrientation(rotationMatrix, angle);
        convertToEarthCoordinates(magneticValues,rotationMatrix);
        matrixCalculate();
    }


    private void updateUI() {
        // 传感器返回的数据
        float x=magneticValues[0];
        float y=magneticValues[1];
        float z=magneticValues[2];
        StringBuffer buffer = new StringBuffer();
        mMagneticField.setText("地磁三轴坐标:\n");
        buffer.append("X方向的磁场为：").append(String.format("%.2f", x)).append("\n");
        buffer.append("Y方向的磁场为：").append(String.format("%.2f", y)).append("\n");
        buffer.append("Z方向的磁场为：").append(String.format("%.2f", z)).append("\n");
        mMagneticField.append(buffer);

        buffer.setLength(0);
        mMagneticField.append("accelerometer:\n");
        x = accelerometerValues[0];
        y = accelerometerValues[1];
        z = accelerometerValues[2];
        buffer.append("accelerometer_X：").append(String.format("%.2f", x)).append("\n");
        buffer.append("accelerometer_Y：").append(String.format("%.2f", y)).append("\n");
        buffer.append("accelerometer_Z：").append(String.format("%.2f", z)).append("\n");
        mMagneticField.append(buffer);

        buffer.setLength(0);
        mMagneticField.append("世界坐标:\n");
        buffer.append("世界坐标 X：").append(String.format("%.2f", worldCoordinates[0])).append("\n");
        globle_x = String.valueOf(worldCoordinates[0]);
        buffer.append("世界坐标 Y：").append(String.format("%.2f", worldCoordinates[1])).append("\n");
        globle_y = String.valueOf(worldCoordinates[1]);
        buffer.append("世界坐标 Z：").append(String.format("%.2f", worldCoordinates[2])).append("\n");
        globle_z = String.valueOf(worldCoordinates[2]);
        mMagneticField.append(buffer.toString());

        buffer.setLength(0);
        mMagneticField.append("载体坐标:\n");
        buffer.append("载体坐标 X：").append(String.format("%.2f", load[0])).append("\n");
        load_x = String.valueOf(load[0]);
        buffer.append("载体坐标 Y：").append(String.format("%.2f", load[1])).append("\n");
        load_y = String.valueOf(load[1]);
        buffer.append("载体坐标 Z：").append(String.format("%.2f", load[2])).append("\n");
        load_z = String.valueOf(load[2]);
        mMagneticField.append(buffer.toString());

//        buffer.setLength(0);
//        wifi_strength = wifi.getWifi().toString();
        mMagneticField.append("wifi强度:\n");
        mMagneticField.append(wifi_strength);
    }

    private void matrixCalculate(){

//        for(int i = 0,j=0; i < 9; i+=3,j++)
//        {
//            worldCoordinates[j] = rotationMatrix[i]*magneticValues[0] + rotationMatrix[i+1]*magneticValues[1]+rotationMatrix[i+2]*magneticValues[2];
//        }
        float[] trans_ang = {1,0,0,0,(float)Math.cos(Math.toDegrees(angle[0])),(float)(-1.0*Math.sin(Math.toDegrees(angle[0]))),0,(float)Math.sin(Math.toDegrees(angle[0])),(float)Math.cos(Math.toDegrees(angle[0]))};
        float[] pitching_ang = {(float)Math.cos(Math.toDegrees(angle[1])),0,(float)(-1.0*Math.sin(Math.toDegrees(angle[1]))),0,1,0,(float)Math.sin(Math.toDegrees(angle[1])),0,(float)Math.cos(Math.toDegrees(angle[1]))};
        float[] drift_ang = {(float)Math.cos(Math.toDegrees(angle[2])),(float)(-1.0*Math.sin(Math.toDegrees(angle[2]))),0,(float)Math.sin(Math.toDegrees(angle[1])),(float)Math.cos(Math.toDegrees(angle[2])),0,0,0,1};
        float[] temp_1 = new float[9];
        float[] temp_2 = new float[9];
        for(int i = 0,k = 0;i<9;i+=3)
        {
            for(int j = 0; j < 3; j++)
            {
                temp_1[k] = trans_ang[i]*pitching_ang[j]+trans_ang[i+1]*pitching_ang[j+3]+trans_ang[i+2]*pitching_ang[j+6];
                k++;
            }
        }

        for(int i = 0,k = 0;i<9;i+=3)
        {
            for(int j = 0; j < 3; j++)
            {
                temp_2[k] = temp_1[i]*drift_ang[j]+temp_1[i+1]*drift_ang[j+3]+temp_1[i+2]*drift_ang[j+6];
                k++;
            }
        }

        for(int i = 0,j=0; i < 9; i+=3,j++)
        {
            load[j] = temp_2[i]*worldCoordinates[0] + temp_2[i+1]*worldCoordinates[1]+temp_2[i+2]*worldCoordinates[2];
        }
    }

    private void convertToEarthCoordinates(float[] magneticData, float[] rotationMatrix) {
        // 应用旋转矩阵，将地磁坐标转换为世界坐标系
        worldCoordinates[0] = rotationMatrix[0] * magneticData[0] +
                rotationMatrix[1] * magneticData[1] +
                rotationMatrix[2] * magneticData[2];

        worldCoordinates[1] = rotationMatrix[3] * magneticData[0] +
                rotationMatrix[4] * magneticData[1] +
                rotationMatrix[5] * magneticData[2];

        worldCoordinates[2] = rotationMatrix[6] * magneticData[0] +
                rotationMatrix[7] * magneticData[1] +
                rotationMatrix[8] * magneticData[2];

    }
}


